<?php

namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\admin\model\AuthRule;
use think\Controller;
use think\Request;

class AuthGroupController extends BaseController
{
    /**
     * 角色列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $groups = AuthGroup::paginate(5);
        $rules = AuthRule::all();
        return view('index', compact('groups', 'rules'));
    }

    /**
     * 添加
     * @param Request $request
     * @return \think\response\View|void
     * @throws \think\exception\DbException
     */
    public function add(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post();
            $validate = $this->validate($data, [
                'title|角色名称' => 'require|unique:auth_group',
                'rules|权限名称' => 'require',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            //halt($data['rules']);
            //将数组转为字符串
            $data['rules'] = implode(',', $data['rules']);
            $data['create_at']=time();
            $data['update_at']=time();
            $result = AuthGroup::create($data);
            if ($result) {
                return $this->success('添加成功', 'index');
            } else {
                return $this->error('添加失败', 'add');
            }
        }
        $rules = AuthRule::all();
        return view('add', compact('rules'));
    }

    /**
     * 修改
     * @param Request $request
     * @param $id
     * @return \think\response\View|void
     * @throws \think\exception\DbException
     */
    public function edit(Request $request, $id)
    {
        $group = AuthGroup::get($id);
        if ($request->isPost()) {
            $data = $request->post();
            $validate = $this->validate($data, [
                'title|角色名称' => 'require',
                'rules|权限名称' => 'require',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            //将数组转为字符串
            $data['rules'] = implode(',', $data['rules']);
            $data['update_at']=time();
            $res = $group->save($data);
            if ($res) {
                return $this->success('修改成功', 'index');
            } else {
                return $this->error('修改失败', 'edit');
            }
        }
        $rules = AuthRule::all();
        return view('edit', compact('rules', 'group'));
    }

    /**
     * 删除
     * @param $id
     * @throws \think\exception\DbException
     */
    public function del($id)
    {
        $group = AuthGroup::get($id);
        $res = $group->delete();
        if ($res) {
            return $this->success('删除成功', 'index');
        } else {
            return $this->error('删除失败', 'index');
        }
    }
}
